//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by liyue on 15/11/8.
//  Copyright © 2015年 李越. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let account = UserAccount.loadAccount()
        print(account)
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        //设置主题色
        setThemeColor()
        //注册通知
        registerNotification()
//        isNewVersion()
        
        window?.rootViewController = defaultRootController()
        return true
    }
    
    //监听通知
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: AppSwitchRootViewControler, object: nil)
    }
    
    @objc private func switchToRootVC(n: NSNotification) {
        
        if (n.object as? String) != nil {
            window?.rootViewController = WelComeViewController()
            return
        }
        window?.rootViewController = MainViewController()
    }
    
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func defaultRootController() -> UIViewController {
        
        if UserAccountViewModel().userLogin {
            
            return isNewVersion() ? NewFeatureViewController() : WelComeViewController()
        }
        return MainViewController()
    }
    
    private func setThemeColor() {
        
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }

    //检查是否是新版本
    private func isNewVersion() -> Bool {
        //获取新版本
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionStr)
        //获取旧版本
        let key = "sandBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        
        userdefaults.setDouble(versionNum!, forKey: key)
        userdefaults.synchronize()
        
        return versionNum! > lastVersion
    }


}

